package com.gopay.common.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * 字符串工具类
 * 
 * @author zhanglei - 2012-11-16
 */
public class StringTools {
    /**
     * 返回对象的字符串表示
     */
    public static final String get(Object obj) {
        return ToStringBuilder.reflectionToString(obj);
    }

    /**
     * checkNulltoString.
     * 
     * @param obj
     *            obj
     * @return String
     */
    public static String checkNulltoString(Object obj) {
        String retStr = "";
        if (null != obj) {
            return obj.toString();
        }
        return retStr;
    }

    private static List<String> specs = new ArrayList<String>();
    static {

//        specs.add("-"); //中划线不算特殊字符 wanggang20150401
        specs.add("_");
    	specs.add("%");
        specs.add("*");
        specs.add("[");
        specs.add("^");
    }

    public static boolean checkSQLLike(String str) {
        boolean check = false;
        for (String spec : specs) {
            if (str.indexOf(spec) > -1) {
                str = str.replace(spec, "/" + spec);
                check = true;
                break;
            }

        }
        return check;

    }

    public static String replaceSQLLike(String str) {

        for (String spec : specs) {
            if (str.indexOf(spec) > -1) {
                str = str.replace(spec, "/" + spec);

            }

        }
        str = "'%" + str + "%' ";
        return str;
    }

    public static String replaceHQLLike(String str) {

        for (String spec : specs) {
            if (str.indexOf(spec) > -1) {
                str = str.replace(spec, "/" + spec);

            }

        }
        return str;
    }

    /**
     * 统计所占字节数(一个中文或全角字符占2个字节,一个ascii字符占1个字节),以便保存到数据库不超长
     * charType取值:gbk,utf8
     * 【依据：oracle中varchar2类型的默认编码GBK时的所占字节数规则】
     * 
     * @author fanghw
     * @param s
     * @return
     */
    public static int getLengthOfByte(String s,String charType) {
        int count = 0;
        if(s==null||"".equals(s)){
            return 0;
        }
        
        //汉字所占字节数
        int chByte=2;
        if("gbk".equals(charType)){
            chByte=2;
        }else if("utf-8".equalsIgnoreCase(charType)||"utf8".equalsIgnoreCase(charType)){
            chByte=3;
        }

        // ascii码字符个数
        int asciiNum = 0;
        String regEx = "[\\u0000-\\u007f]";
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(regEx);
        java.util.regex.Matcher m = p.matcher(s);
        while (m.find()) {
            asciiNum++;
        }

        count = asciiNum + (s.length() - asciiNum) * chByte;

        return count;
    }

    
}
